# Priority Abstraction Layer stub file (?)
from reader.models import *
from backend.digg import *
from settings import DIGG_API_KEY
from datetime import *
import re

def update_digg_stories():
  digg = Digg(DIGG_API_KEY)
  topics = digg.getTopics()
  mapped_topic_articles = {'images': []}
  for topic in topics:
    mapped_topic_name = map_digg_topic(topic.name)
    if not mapped_topic_articles.has_key(mapped_topic_name):
      mapped_topic_articles[mapped_topic_name] = []
    stories = digg.getTopicPopularStories(topic.short_name, count=5)
    for story in stories:
      story_topic_name = mapped_topic_name
      if re.compile("[^?]*(jpg|jpeg|png|gif)$", re.IGNORECASE).match(story.link):
        print story.link
        story_topic_name = 'images'
        story.img_url = story.link
      else:
        story.img_url = ''
      story.topic = story_topic_name
      mapped_topic_articles[story_topic_name].append(story)

  for topic in mapped_topic_articles.keys():
    articles = mapped_topic_articles[topic]
    diggs = map(lambda story: int(story.diggs), articles)
    if len(diggs) > 0:
      max_topic_diggs = max(diggs)
    else:
      max_topic_diggs = 0
    print "*** " + topic + " ***"
    print max_topic_diggs
    for story in articles:
      story.priority = (float(story.diggs)/float(max_topic_diggs)) * 10.0 # scale from 1 - 10
      try:
        print "%s (%s vs . %s)" % (story.title, story.diggs, story.priority)
      except:
        pass
      add_story_to_db(story, 'Digg')
    print "\n"

def add_story_to_db(story, source):
  existing = None
  try:
    existing = Story.objects.get(url=story.link)
  except:
    pass
  if existing == None:
    s = Story(title=story.title, description=story.description, category=story.topic, url=story.link, date_time=datetime.fromtimestamp(int(story.submit_date)), priority=story.priority, source=source, img_url=story.img_url)
    s.save()
  else:
    print "%s existed" % story.link

if __name__ == '__main__':
  update_digg_stories()
